import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import requests
import config
from SysInfo import Informator
from ftplib import FTP

informator = Informator()
class MyHandler(FTPHandler):

    def on_connect(self):
        print("Client connected")

    def on_disconnect(self):
        print("Client disconnected")

    def on_login(self, username):
        print("User "+username+" has been connected")
        pass

    def on_logout(self, username):
        print("User "+username+" has been disconnected")

    def on_file_sent(self, file):
        # do something when a file has been sent
        pass

    def on_file_received(self, file):
        nodes = str(requests.get(f"{config.ip}/nodes_list").text).split(",")
        for node in nodes:
            if node==str(informator.ip):
                continue
            else:
                ftp = FTP()
                ftp.connect(node)
                ftp.login("user", "12345")
                with open(file, "rb") as f:
                    # Command for Uploading the file "STOR filename"
                    ftp.storbinary(f"STOR {file}", f)
                ftp.dir()
                ftp.close()
        pass

    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        pass

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        import os
        os.remove(file)

        #send msg of error

class FTPS:
    def __init__(self,username,password,path):
        self.username = username
        self.password = password
        self.path = path

    def start_server(self,address):
        authorizer = DummyAuthorizer()
        authorizer.add_user(self.username,self.password,self.path, perm='elradfmwMT')
        authorizer.add_anonymous(os.getcwd())

        handler = MyHandler
        handler.authorizer = authorizer
        handler.banner = "pyftpdlib based ftpd ready."

        server = FTPServer(address, handler)
        server.max_cons = 256
        server.max_cons_per_ip = 5
        server.serve_forever()
